<template>
  <div>
    <!-- 面包屑导航区域 -->
    <breadcrumb :breadcrumbs="breadcrumbs" />

    <!-- 卡片视图区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCateClick"
            >添加分类</el-button
          >
        </el-col>
      </el-row>

      <!-- 表格 selection-type:是否显示复选框 expand-type：是否允许下拉-->
      <tree-table
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
        class="treetable"
      >
        <!-- 是否有效 -->
        <template v-slot:isok="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted == false"
            style="color: green"
          >
          </i>
          <i class="el-icon-error" v-else style="color: red"></i>
        </template>

        <!-- 排序 -->
        <template v-slot:order="scope">
          <el-tag v-if="scope.row.cat_level == 0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level == 1"
            >二级</el-tag
          >
          <el-tag type="warning" v-else>三级</el-tag>
        </template>

        <!-- 操作 -->
        <template v-slot:opt="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="editCateDialog(scope.row.cat_id)"
          >
            编辑
          </el-button>
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="removeCate(scope.row.cat_id)"
          >
            删除
          </el-button>
        </template>
      </tree-table>

      <!--分页  -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible="addCateDialogVisible"
      width="50%"
      @close="addCateDialogClosed"
    >
      <!-- 内容主体 -->
      <el-form
        :model="addCateForm"
        :rules="addCateFormRules"
        ref="addCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称:" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类:">
          <div class="block">
            <el-cascader
              v-model="selectKeys"
              :options="parentCateList"
              :props="cascaderProps"
              @change="parentCateChange"
              clearable
            ></el-cascader>
          </div>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addCateDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addCateClick">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑分类 -->
    <el-dialog
      title="编辑分类"
      :visible="editCateDialogVisible"
      width="50%"
      @close="editCateDialogClosed"
    >
      <!-- 内容主体 -->
      <el-form
        :model="editCateForm"
        :rules="editCateFormRules"
        ref="editCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称:" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editCateDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editCateClick">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import Breadcrumb from "@/components/Breadcrumb";

import {
  getCategories,
  addCategory,
  editCategory,
  deleteCateById,
} from "@/network/goods/cate";
export default {
  name: "Cate",
  data() {
    return {
      breadcrumbs: ["商品管理", "商品分类"],
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      cateList: [],
      total: 0,
      columns: [
        //为table指定列的定义
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",
          type: "template", //表示将该列定义为模板列
          template: "isok", //表示当前这一列使用的模板名称
        },
        {
          label: "排序",
          type: "template", //表示将该列定义为模板列
          template: "order", //表示当前这一列使用的模板名称
        },
        {
          label: "操作",
          type: "template", //表示将该列定义为模板列
          template: "opt", //表示当前这一列使用的模板名称
        },
      ],
      addCateDialogVisible: false, //添加分类对话框
      //添加分类表单对象
      addCateForm: {
        cat_name: "",
        cat_pid: 0,
        cat_level: 0,
      },
      //添加分类表单对象验证对象
      addCateFormRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      parentCateList: [], //父级分类列表
      //级联选择器的配置
      cascaderProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
        checkStrictly: "true",
      },
      //选中的父级分类id数组
      selectKeys: [],
      //编辑分类表单对象
      editCateForm: {
        cat_name: "",
      },
      editCateFormRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      editCateDialogVisible: false, //编辑分类对话框
      editCateId: 0, //编辑分类id
    };
  },
  components: {
    Breadcrumb,
  },
  methods: {
    getCates() {
      getCategories(
        this.queryInfo.type,
        this.queryInfo.pagenum,
        this.queryInfo.pagesize
      ).then((res) => {
        if (res.meta.status != 200)
          return this.$message.error("获取商品分类列表失败！" + res.meta.msg);
        this.cateList = res.data.result;
        this.total = res.data.total;
        this.$message.success("获取商品分类列表成功！");
      });
    },

    //监听pagesize改变
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getCates();
    },
    //监听pageNum变化
    handleCurrentChange(newNum) {
      this.queryInfo.pagenum = newNum;
      this.getCates();
    },
    //添加分类对话框
    showAddCateClick() {
      /**获取父级所有分类 */
      getCategories(2, 1, 100000).then((res) => {
        if (res.meta.status != 200)
          return this.$message.error("获取商品分类列表失败！" + res.meta.msg);
        this.parentCateList = res.data.result;
      });
      this.addCateDialogVisible = true;
    },
    //选中项发生变化触发
    parentCateChange() {
      //如果selectKeys 数组中的length大于0，证明选中的是父级分类
      if (this.selectKeys.length > 0) {
        this.addCateForm.cat_pid = this.selectKeys[this.selectKeys.length - 1]; //取最后一项父id
        this.addCateForm.cat_level = this.selectKeys.length; //未当前分类的等级赋值
        return;
      } else {
        this.addCateForm.cat_level = this.addCateForm.cat_pid = 0;
      }
    },

    //添加分类
    addCateClick() {
      //规则校验
      this.$refs.addCateFormRef.validate((valid) => {
        if (!valid) return;
        addCategory(this.addCateForm).then((res) => {
          if (res.meta.status != 201)
            return this.$message.error("添加分类失败！" + res.meta.msg);
          this.$message.success("添加分类成功！");
          this.getCates();
          this.addCateDialogVisible = false;
        });
      });
    },

    //监听对话框的关闭
    addCateDialogClosed() {
      this.$refs.addCateFormRef.resetFields();
      this.selectKeys = [];
      this.addCateForm.cat_level = this.addCateForm.cat_pid = 0;
    },
    //编辑分类对话框弹出
    editCateDialog(cateId) {
      this.editCateDialogVisible = true;
      this.editCateId = cateId;
    },
    //编辑分类名称
    editCateClick() {
      this.$refs.editCateFormRef.validate((valid) => {
        if (!valid) return;
        editCategory(this.editCateId, this.editCateForm).then((res) => {
          if (res.meta.status != 200)
            return this.$message.error("编辑分类失败！" + res.meta.msg);
          this.$message.success("编辑分类成功！");
          this.getCates();
          this.editCateDialogVisible = false;
        });
      });
    },

    editCateDialogClosed() {
      this.$refs.editCateFormRef.resetFields();
    },
    //删除分类
    removeCate(id) {
      this.$confirm("此操作将永久删除该分类, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteCateById(id).then((res) => {
            if (res.meta.status != 200)
              return this.$message.error("删除失败！" + res.meta.msg);
            this.$message.success("删除成功");
            this.getCates();
          });
        })
        .catch(() => {
          this.$message.info("已取消删除！");
        });
    },
  },
  created() {
    this.getCates();
  },
};
</script>

<style lang="less" scoped>
.treetable {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}
</style>    